const express     = require('express');
const app         = express();

// 引入body-parser用于解析post参数
var bodyParser = require('body-parser');

// 需要use的 application/json
app.use(bodyParser.json()); 
// application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: true
})); 

const constants     = require('./data/constants');
const sipServer     = require('./sip/server');
const dbManager     = require('./db/dbmanager');
const settingModel  = require('./model/setting');
const mediaserverModel = require('./model/mediaserver');
const mediaCtrl     = require('./controller/v1/media');
const log4js        = require('./data/log');
const logger        = log4js.getLogger('request');
const scheduleCtrl  = require('./pipe/schedule');
const alertsCtrl    = require('./pipe/alerts');
const adminCtrl     = require('./controller/v1/admin');
const mediaServerCtrl = require('./controller/v1/mediaserver');

// 设置express日志
log4js.useLogger(app,logger);

// express 引入静态资源
const static = express.static('public');
app.use(static);

// express 引入路由
app.use(require('./routers/mediaserver'));
app.use(require('./routers/service'));
app.use(require('./routers/media'));
app.use(require('./routers/channel'))
app.use(require('./routers/device'))
app.use(require('./routers/admin'));
app.use(require('./routers/setting'));
app.use(require('./routers/alerts'));
app.use(require('./routers/timing'));

process.on('SIGINT', () => {
  logger.info('停止服务，保存临时文件，停止计划任务');
  scheduleCtrl.stop();
  constants.save(async ()=>{
    dbManager.close();
    process.exit(0);
  });
});

// 捕获异常
process.on('unhandledRejection', (reason, p) => {
  logger.error('Unhandled Rejection at:', p, 'reason:', reason);
  console.trace(p);
});

//TODO:加载权限管理 https://github.com/OptimalBits/node_acl

/**
 * 启动 http 服务
 */ 
let server = app.listen(constants.http.port, function () {
  let host = server.address().address;
  let port = server.address().port;
  logger.info("启动 Web 服务: http://%s:%s", host, port);
  
  /**从数据库加载配置 */
  dbManager.open();

  // 恢复上次关闭前的设置
  constants.load(async ()=>{
    // 如果没有管理员信息则新建默认账号
    await adminCtrl.init();
    await mediaServerCtrl.init();
    // 监控ftp文件夹，如果有数据则先处理
    if(alertsCtrl.init()){
      // 监控文件夹，如果有新文件就处理
      alertsCtrl.inspect();
  
      let sipSetting = await settingModel.load();
      
      // 加载medisServer信息
      let medias = await mediaserverModel.list(0, 10000);
      let connect = true;
      for(var a in medias){
        const item = medias[a];
        const alive=true;
        // 下面用来检测媒体服务器是否正常
        // const alive =await mediaCtrl.ping(item.server_id);
        if(alive){
          logger.info('准备释放 rtp 资源 %s', item.server_id);
          mediaCtrl.resetRtpServer(item.server_id);
        }else{
          logger.error("无法连接媒体服务器,server: ", item)
          connect = false;
        }
      }
      if(connect){
        logger.info('启动计划任务检查日志文件');
        scheduleCtrl.start();
        logger.info('启动GB28181的sip服务');
        sipServer.start(sipSetting);
      }else{
        logger.info('程序将退出，请检查ZLMediaKit是否正常启动');
        process.exit(0)
      }
    }else{
      logger.warn('程序将退出，请检查截图文件夹是否能访问');
      process.exit(0)
    }
  });
});